﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ContactManager.Common;
using System.Data.OleDb;

namespace ContactManager
{
    public partial class HomeFrm : AlSkin.AlForm.AlBaseForm
    {
        bool LabEnterFlag = false;

        //定义窗口
        public static LogFrm lf;
        public static IncFrm icf;
        public static WorkIncPayFrm wip;
        public static WeekReportFrm wrf;
        public static SmsFrm sf;
        public static IncMonthFrm imf;
        public static IncYearFrm iyf;
        public static YearWorkIncPayFrm ywip;
        public static MonthReportFrm mrf;
        public static YearReportFrm yrf;
        public static TypeAndSubFrm tsfrm;
        public static GroupFrm gf;

        public HomeFrm()
        {
            InitializeComponent();
        }

        ContactFrm cf = new ContactFrm();

        private void combPromary_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.combCity.Items.Clear();
            string sql = "select cityName from city,promary where city.proID=promary.proID and promary.proName='" + this.combPromary.Text.Trim() + "'";
            DataSet ds = AccessHelper.ExecuteQuery(sql);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string cityName = dr["cityName"].ToString();
                this.combCity.Items.Add(cityName);
            }
        }

        private void showCf()
        {
            cf.Location = new Point(this.Left, this.Top + this.Height - 10);
            cf.Show();
            cf.clearDataGridView();
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            string name = this.txtName.Text.Trim();
            string pname = this.txtPname.Text.Trim();
            DateTime birthday = this.dtpBirthday.Value;
            string company = this.txtCompany.Text.Trim();
            string title = this.txtTitle.Text.Trim();
            string qq = this.txtQQ.Text.Trim();
            string msn = this.txtMSN.Text.Trim();
            string phone1 = this.txtPhone1.Text.Trim();
            string phone2 = this.txtPhone2.Text.Trim();
            string mail = this.txtMail.Text.Trim();
            string cphone = this.txtCompanyPhone.Text.Trim();
            string url = this.txtUrl.Text.Trim();
            string promary = this.combPromary.Text.Trim();
            string city = this.combCity.Text.Trim();
            string addressDetals = this.txtAddressDetails.Text.Trim();
            string address = promary + "," + city + "," + addressDetals;
            ComboBoxItem cbiGroup = (ComboBoxItem)this.combGroup.SelectedItem;

            //生成sql
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from contacters t where 1 = 1");
            if (name.Length != 0)
            {
                sb.Append(" and t.c_name like '%" + name + "%'");
            }
            if (pname.Length != 0)
            {
                sb.Append(" and t.c_pname like '%" + pname + "%'");
            }
            if (company.Length != 0)
            {
                sb.Append(" and t.c_company like '%" + company + "%'");
            }
            if (title.Length != 0)
            {
                sb.Append(" and t.c_title like '%" + title + "%'");
            }
            if (qq.Length != 0)
            {
                sb.Append(" and t.c_qq like '%" + qq + "%'");
            }
            if (msn.Length != 0)
            {
                sb.Append(" and t.c_msn like '%" + msn + "%'");
            }
            if (phone1.Length != 0)
            {
                sb.Append(" and t.c_phone_one like '%" + phone1 + "%'");
            }
            if (phone2.Length != 0)
            {
                sb.Append(" and t.c_phone_second like '%" + phone2 + "%'");
            }
            if (mail.Length != 0)
            {
                sb.Append(" and t.c_email like '%" + mail + "%'");
            }
            if (cphone.Length != 0)
            {
                sb.Append(" and t.c_company_phone like '%" + cphone + "%'");
            }
            if (url.Length != 0)
            {
                sb.Append(" and t.c_url like '%" + url + "%'");
            }
            if (promary.Length != 0)
            {
                sb.Append(" and t.c_address like '%" + address + "%'");
            }
            if (this.combGroup.Text.Trim().Length != 0)
            {
                sb.Append(" and t.c_group_id like '%" + cbiGroup.Value.ToString() + "%'");
            }
            sb.Append(" order by t.c_id desc");
            //填充数据
            showCf();

            DataSet ds = AccessHelper.ExecuteQuery(sb.ToString());
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                int id = Convert.ToInt32(dr["c_id"].ToString());
                string dname = dr["c_name"].ToString();
                string dphone1 = dr["c_phone_one"].ToString();
                string dphone2 = dr["c_phone_second"].ToString();
                string dcphone = dr["c_company_phone"].ToString();
                string dcompany = dr["c_company"].ToString();

                cf.setDataGridView(id, dname, dphone1 + "/" + dphone2, dcphone, dcompany);
            }

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string name = this.txtName.Text.Trim();
            string pname = this.txtPname.Text.Trim();
            DateTime birthday = this.dtpBirthday.Value;
            string company = this.txtCompany.Text.Trim();
            string title = this.txtTitle.Text.Trim();
            string qq = this.txtQQ.Text.Trim();
            string msn = this.txtMSN.Text.Trim();
            string phone1 = this.txtPhone1.Text.Trim();
            string phone2 = this.txtPhone2.Text.Trim();
            string mail = this.txtMail.Text.Trim();
            string cphone = this.txtCompanyPhone.Text.Trim();
            string url = this.txtUrl.Text.Trim();
            string promary = this.combPromary.Text.Trim();
            string city = this.combCity.Text.Trim();
            string addressDetals = this.txtAddressDetails.Text.Trim();
            string address = promary + "," + city + "," + addressDetals;
            ComboBoxItem cbiGroup = (ComboBoxItem)this.combGroup.SelectedItem;

            if (this.txtName.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入姓名，红色标签的项目为必填项", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (this.txtTitle.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入职务，红色标签的项目为必填项", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (this.txtPhone1.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入电话1，红色标签的项目为必填项", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (this.combGroup.Text.Trim().Length == 0)
            {
                MessageBox.Show("请选择分组，红色标签的项目为必填项", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }


            if (DialogResult.Yes == MessageBox.Show("确认添加吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                //保存数据，遇到日期转换问题。
                StringBuilder sb = new StringBuilder("insert into contacters(c_name,c_pname,c_company,c_title,c_qq,c_msn,c_phone_one,c_phone_second,c_email,c_company_phone,c_url,c_address,c_group_id,c_birthday) values(?,?,?,?,?,?,?,?,?,?,?,?,?,#" + birthday.ToString("yyyy/MM/dd HH:mm:ss") + "#)");
                OleDbParameter[] parameters = {new OleDbParameter("@c_name",name),
                                               new OleDbParameter("@c_pname",pname),
                                               new OleDbParameter("@c_company",company),
                                               new OleDbParameter("@c_title",title),
                                               new OleDbParameter("@c_qq",qq),
                                               new OleDbParameter("@c_msn",msn),
                                               new OleDbParameter("@c_phone_one",phone1),
                                               new OleDbParameter("@c_phone_second",phone2),
                                               new OleDbParameter("@c_email",mail),
                                               new OleDbParameter("@c_company_phone",cphone),
                                               new OleDbParameter("@c_url",url),
                                               new OleDbParameter("@c_address",address),
                                               new OleDbParameter("@c_group_id",Convert.ToInt32(cbiGroup.Value))
                                              };
                if (AccessHelper.ExecuteNonQuery(sb.ToString(), parameters) > 0)
                {
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.btnAll_Click(this, null);
                }
                else
                {
                    MessageBox.Show("抱歉，出错了", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }     
            }
        }

        private void btnAll_Click(object sender, EventArgs e)
        {
            
            string sql = "select t.c_id,t.c_name,t.c_phone_one,t.c_phone_second,t.c_company_phone,t.c_company from contacters t order by t.c_id desc";
            DataSet ds = AccessHelper.ExecuteQuery(sql);
            showCf();
            foreach( DataRow dr in ds.Tables[0].Rows )
            {
                int id = Convert.ToInt32(dr["c_id"].ToString());
                string name = dr["c_name"].ToString();
                string phone1 = dr["c_phone_one"].ToString();
                string phone2 = dr["c_phone_second"].ToString();
                string cphone = dr["c_company_phone"].ToString();
                string company = dr["c_company"].ToString();
                cf.setDataGridView(id, name, phone1 + "/" + phone2, cphone, company);
            }
        }

        private void HomeFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("您确定要退出吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
            {
                this.notifyIconMain.Dispose();
                this.Dispose();
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("您确定要退出吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
            {
                this.Dispose();
                Application.Exit();
            }
        }

        private void SetUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RegisterFrm rf = new RegisterFrm();
            rf.Show();
        }

        private void notifyIconMain_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.notifyIconMain.Visible = false;
        }

        private void timerMain_Tick(object sender, EventArgs e)
        {
            //设置托盘
            this.notifyIconMain.Text = "人际通\n当前时间为 :" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //this.notifyIconMain.ShowBalloonTip(10, "提示", "hello",ToolTipIcon.Info);
            //利用气泡来提示快到时约会（待做）

            if (!LabEnterFlag)
            {
                int fWidth = this.panelAD.Width;
                int fHeight = this.panelAD.Height;
                Point lPos = new Point(this.labAD.Location.X, this.labAD.Location.Y);
                if (this.labAD.Width + lPos.X > 0)
                {
                    this.labAD.Location = new Point(lPos.X - 1, lPos.Y);
                    return;
                }
                else
                {
                    this.labAD.Location = new Point(this.panelAD.Location.X + this.Width, 0);
                }
            }
        }

        private void ExportExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataSet ds = AccessHelper.ExecuteQuery("select * from contacters");
            string[] headers = { "姓名", "昵称", "生日", "公司名称", "职务", "qq", "msn", "手机1", "手机2", "电邮", "公司电话", "网址", "爱好", "地址" };
            ExcelUtil.saveAs(ds, headers, this.progressBarMain);
        }

        private void ImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExcelUtil.importContacters(this.progressBarMain);
        }

        private void SetGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gf == null)
            {
                gf = new GroupFrm();
                gf.Show();
            }
            else
            {
                gf.Activate();
            }
        }

        private void DailyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lf == null)
            {
                lf = new LogFrm();
                lf.Show();
            }
            else
            {
                lf.Activate();
            }
        }

        private void SetTypeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tsfrm == null)
            {
                tsfrm = new TypeAndSubFrm();
                tsfrm.Show();
            }
            else
            {
                tsfrm.Activate();
            }
        }

        private void IncPayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (icf == null)
            {
                icf = new IncFrm();
                icf.Show();
            }
            else
            {
                icf.Activate();
            }
        }

        private void IncMonthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (imf == null)
            {
                imf = new IncMonthFrm();
                imf.Show();
            }
            else
            {
                imf.Activate();
            }
        }

        private void HomeFrm_Load(object sender, EventArgs e)
        {
            try
            {
                //启动设置用户
                int userNum = AccessHelper.ExecuteScalar("select count(*) from users");
                if (userNum != 1)
                {
                    RegisterFrm rf = new RegisterFrm();
                    rf.ShowDialog();
                }
                else
                {
                    DataSet ds = AccessHelper.ExecuteQuery("select * from users");
                    GlobleUser.USER_ID = ds.Tables[0].Rows[0][0].ToString();
                    GlobleUser.USER_NAME = ds.Tables[0].Rows[0][1].ToString();
                }

                ////---------------------------修改窗体高度
                this.dtpBirthday.Value = new DateTime(1980, 1, 1);
                this.dataGridViewRemind.Rows.Clear();

                //提醒数据填充
                //获取最靠近当前时间的前50个约会
                //需要修改
                int i = 0;

                //设置现在到昨天的25条
                string remindSql = "select top 25 t1.c_name,t2.t_next_content,t1.c_id,t2.t_next_time from contacters t1,traces t2 where t1.c_id = t2.t_c_id and t2.t_next_time >= DateAdd('d',-1,now()) and t2.t_next_time < now() order by t2.t_next_time asc";
                DataSet remindDs = AccessHelper.ExecuteQuery(remindSql);
                foreach (DataRow dr in remindDs.Tables[0].Rows)
                {
                    string contactName = dr[0].ToString();
                    string traceContent = dr[1].ToString();
                    string c_id = dr[2].ToString();
                    string time = dr[3].ToString();

                    this.dataGridViewRemind.Rows.Add(c_id, time, contactName + "," + traceContent);
                    i++;
                }
                //设置现在以后的25条
                string remindNSql = "select top 25 t1.c_name,t2.t_next_content,t1.c_id,t2.t_next_time from contacters t1,traces t2 where t1.c_id = t2.t_c_id and t2.t_next_time >=now() order by t2.t_next_time asc";
                DataSet remindNDs = AccessHelper.ExecuteQuery(remindNSql);
                foreach (DataRow dr in remindNDs.Tables[0].Rows)
                {
                    string contactName = dr[0].ToString();
                    string traceContent = dr[1].ToString();
                    string c_id = dr[2].ToString();
                    string time = dr[3].ToString();

                    this.dataGridViewRemind.Rows.Add(c_id, time, contactName + "," + traceContent);
                }
                if (i - 2 >= 0)
                {
                    this.dataGridViewRemind.Rows[i - 1].Selected = true;
                    this.dataGridViewRemind.FirstDisplayedScrollingRowIndex = this.dataGridViewRemind.Rows[i - 2].Index;
                }
                else if (i - 1 >= 0)
                {
                    this.dataGridViewRemind.Rows[i - 1].Selected = true;
                    this.dataGridViewRemind.FirstDisplayedScrollingRowIndex = this.dataGridViewRemind.Rows[i - 1].Index;
                }
                

                //this.dataGridViewRemind.Rows[0].DefaultCellStyle.BackColor = Color.Gray;
                //设置每行的颜色
                //-------------------------------------------------------------------------

                //启动时间线程
                this.timerMain.Enabled = true;

                //设置窗口位置
                this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - this.Width, 0);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            

        }

        public void allButton()
        {
            this.btnAll_Click(this, null);
        }

        private void IncYearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (iyf == null)
            {
                iyf = new IncYearFrm();
                iyf.Show();
            }
            else
            {
                iyf.Activate();
            }
        }

        private void WeekReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (wrf == null)
            {
                wrf = new WeekReportFrm();
                wrf.Show();
            }
            else
            {
                wrf.Activate();
            }
        }

        private void combGroup_MouseClick(object sender, MouseEventArgs e)
        {
            //分组
            this.combGroup.Items.Clear();
            string groupSql = "select g_id,g_name from groups order by g_sort asc";
            DataSet groupDs = AccessHelper.ExecuteQuery(groupSql);
            foreach (DataRow dr in groupDs.Tables[0].Rows)
            {
                ComboBoxItem combItem = new ComboBoxItem();
                int groupId =Convert.ToInt32(dr[0].ToString());
                string groupName = dr[1].ToString();
                combItem.Text = groupName;
                combItem.Value = groupId;
                this.combGroup.Items.Add(combItem);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            this.txtAddressDetails.Clear();
            this.txtCompany.Clear();
            this.txtCompanyPhone.Clear();
            this.txtMail.Clear();
            this.txtMSN.Clear();
            this.txtName.Clear();
            this.txtPhone1.Clear();
            this.txtPhone2.Clear();
            this.txtPname.Clear();
            this.txtQQ.Clear();
            this.txtTitle.Clear();
            this.txtUrl.Clear();
            this.dtpBirthday.Value = new DateTime(1980, 1, 1);
            this.combCity.Items.Clear();
            this.combGroup_MouseClick(this, null);
            this.combPromary_MouseClick(this, null);
        }

        private void MonthReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (mrf == null)
            {
                mrf = new MonthReportFrm();
                mrf.Show();
            }
            else
            {
                mrf.Activate();
            }
        }

        private void YearReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (yrf == null)
            {
                yrf = new YearReportFrm();
                yrf.Show();
            }
            else
            {
                yrf.Activate();
            }
        }

        private void combPromary_MouseClick(object sender, MouseEventArgs e)
        {
            //combbox数据填充
            //省
            this.combPromary.Items.Clear();
            string promarySql = "select proName from promary";
            DataSet promaryDs = AccessHelper.ExecuteQuery(promarySql);
            foreach (DataRow dr in promaryDs.Tables[0].Rows)
            {
                string proName = dr[0].ToString();
                this.combPromary.Items.Add(proName);
            }
        }

        private void WorkIncPayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (wip == null)
            {
                wip = new WorkIncPayFrm();
                wip.Show();
            }
            else
            {
                wip.Activate();
            }
        }

        private void YearWorkIncToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ywip == null)
            {
                ywip = new YearWorkIncPayFrm();
                ywip.Show();
            }
            else
            {
                ywip.Activate();
            }
        }

        private void SmsSendToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (sf == null)
            {
                sf = new SmsFrm();
                sf.Show();
            }
            else
            {
                sf.Activate();
            }
        }

        private void pictureBoxMain_Paint(object sender, PaintEventArgs e)
        {
            //改变边框颜色
            PictureBox p = (PictureBox)sender;
            Pen pp = new Pen(Color.FromArgb(23, 169, 254));
            e.Graphics.DrawRectangle(pp, e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.X + e.ClipRectangle.Width - 1, e.ClipRectangle.Y + e.ClipRectangle.Height - 1); 
        }

        private void dataGridViewRemind_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridViewRemind.CurrentRow != null)
            {
                TracesForm tf = new TracesForm(dataGridViewRemind.CurrentRow.Cells["c_id"].Value.ToString());
                tf.ShowDialog();
            }
        }

        private void txtQQ_KeyPress(object sender, KeyPressEventArgs e)
        {
            checkTextBox(e);
        }

        private static void checkTextBox(KeyPressEventArgs e)
        {
            if (((e.KeyChar < (char)48) || (e.KeyChar > (char)57)) && e.KeyChar != 8)
            {
                e.Handled = true;
            }
        }

        private void txtPhone1_KeyPress(object sender, KeyPressEventArgs e)
        {
            checkTextBox(e);
        }

        private void txtPhone2_KeyPress(object sender, KeyPressEventArgs e)
        {
            checkTextBox(e);
        }

        private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }

        private void linkLabelWeb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.renjitong.net");
        }

        private void HomeFrm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                cf.Hide();
                this.Hide();
                this.notifyIconMain.Visible = true;
            }
        }

        private void btnLog_Click(object sender, EventArgs e)
        {
            DailyToolStripMenuItem_Click(this, null);
        }

        private void btnIncPay_Click(object sender, EventArgs e)
        {
            IncPayToolStripMenuItem_Click(this, null);
        }

        private void btnWorkInc_Click(object sender, EventArgs e)
        {
            WorkIncPayToolStripMenuItem_Click(this, null);
        }

        private void btnReport_Click(object sender, EventArgs e)
        {
            WeekReportToolStripMenuItem_Click(this, null);
        }

        private void btnSmsSend_Click(object sender, EventArgs e)
        {
            SmsSendToolStripMenuItem_Click(this, null);
        }

        private void labAD_MouseEnter(object sender, EventArgs e)
        {
            this.LabEnterFlag = true;
        }

        private void labAD_MouseLeave(object sender, EventArgs e)
        {
            this.LabEnterFlag = false;
        }

        private void UpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.renjitong.net");
        }

        private void btnLearn_Click(object sender, EventArgs e)
        {
            MessageBox.Show("只有网络版高级用户才可以使用本功能，请在帮助菜单中升级", "升级提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnAnalysis_Click(object sender, EventArgs e)
        {
            MessageBox.Show("只有网络版VIP用户才可以使用本功能，请在帮助菜单中升级", "升级提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }



    }
}
